using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace IPAMS.Views
{
    /// <summary>
    /// This is an editor for the Stocks table. It enables loading from a file,
    ///saving to a file and more
    /// </summary>
    public partial class StocksEditor : UserControl
    {
        public event EventHandler<TEventArgs<string>> StocksFileSelected;
        public event EventHandler<TEventArgs<bool>> GetCurrencies;    

        public DSIPAMS.DTStocksDataTable stocks;
        string[] stocksHeaders;

        /// <summary>
        /// Initializes a new instance of the <see cref="StocksEditor"/> class.
        /// </summary>
        public StocksEditor()
        {
            InitializeComponent();
            InitializeComponentExtended();
        }

        /// <summary>
        /// Initializes the component extended.
        /// </summary>
        private void InitializeComponentExtended()
        {
            stocks = new DSIPAMS.DTStocksDataTable();
        }

        /// <summary>
        /// Handles the Click event of the buttonBrowseStocks control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonBrowseStocks_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Comma Seperated Values (*.csv)|*.csv";
            ofd.Title = "Select Stocks data file...";
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            DialogResult dr = ofd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                if (StocksFileSelected != null)
                {
                    StocksFileSelected(this, new TEventArgs<string>(ofd.FileName));
                }
            }
        }

        /// <summary>
        /// Handles the DropDown event of the comboBoxCurrencies control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void comboBoxCurrencies_DropDown(object sender, EventArgs e)
        {
            if (GetCurrencies != null)
            {
                GetCurrencies(this, new TEventArgs<bool>(true));
            }
        }

        /// <summary>
        /// Handles the DataSourceChanged event of the dgvStocks control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void dgvStocks_DataSourceChanged(object sender, EventArgs e)
        {
            dgvStocks.Refresh();
        }

        /// <summary>
        /// Loads the data from a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        /// <returns>a DataTable with the file data</returns>
        public DataTable LoadData(string dataFilePath)
        {
            if (File.Exists(dataFilePath))
            {
                StreamReader sr = new StreamReader(dataFilePath);
                stocksHeaders = sr.ReadLine().Split(',');;
                while (true)
                {
                    string stock = sr.ReadLine();
                    if (stock == string.Empty || stock == null) break;
                    string[] stockInfo = stock.Split(',');
                    if (stockInfo.Length != 4) continue;
                    stocks.AddDTStocksRow(stockInfo[0], stockInfo[1], stockInfo[2], stockInfo[3]);
                }
                sr.Close();


                textBoxStocksPath.Text = dataFilePath;
                Text = dataFilePath;

                stocks.AcceptChanges();

                dgvStocks.DataSource = stocks;

                for (int index = 0; index < stocksHeaders.Length; index++)
                {
                    dgvStocks.Columns[index].HeaderText = stocksHeaders[index];
                }



                foreach (DataGridViewColumn column in dgvStocks.Columns)
                {
                    column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }

            }
         
            return stocks;
        }


        /// <summary>
        /// Saves the data to a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        public void SaveData(string dataFilePath)
        {
            StreamWriter sw = new StreamWriter(dataFilePath);
            string fileContent = stocksHeaders + Environment.NewLine;
            foreach (DSIPAMS.DTInvestmentManagementHousesRow stock in stocks)
            {
                fileContent += string.Format("{0},{1},{2}" + Environment.NewLine, stock[0], stock[1],stock[2]);
            }
            sw.Write(fileContent);
            sw.Close();

        }

    }
}
